import config from '../../public/js/myservice/config';

define(function (require, exports, module) {
    var angular = require('angular');
    require("@yunke/jquery_pagination");
    require('angular-ui');
    require("angular-messages");
    require('../../public/js/myservice/common/nav');
    var _ = require('underscore');
    var authorize = require('../../public/js/myservice/authorize');

    var util = require('@yunke/core/util').default;
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    require('../../public/js/myservice/common/row-toolbar');
    var ui = require("@yunke/core/ui");

    require('../../public/misc/mediaUpload/css/style.css');
    require('../../public/misc/mediaUpload/js/jquery.form');
    require('../../public/misc/mediaUpload/js/myUpload');
    require('../css/picture_manager.css');

    angular.module('PictureManager', ['ngUI', 'ngPublicUI', 'myNav', 'rowToolbar', 'ngMessages'])
        .constant('unkown', '未知')
        .constant('picType', {
            1: '登录页底图',
            2: '首页广告图'
        })
        .constant('isAble', {
            0: '否',
            1: '是'
        })
        .constant('pageIndex', 1)
        .constant('pageSize', 10)
        .constant('apis', {
            get: {
                api: '/orgapi/index.php?r=/picture/picture/edit'
            },
            save: {
                api: '/orgapi/index.php?r=/picture/picture/save',
                method: 'post'
            },
            delete: {
                api: '/orgapi/index.php?r=/picture/picture/delete'
            },
            list: {
                api: '/orgapi/index.php?r=/picture/picture/list'
            },
            enable: {
                api: '/orgapi/index.php?r=/picture/picture/whether-able'
            }
        })
        .service('service', ['$http', 'apis', function ($http, apis) {

            return (function (service) {
                _.object(_.each(_.keys(apis), function (apiName) {
                    service[apiName] = createService(apiName);
                }));
                return service;
            })({});

            function createService(name) {
                var api = apis[name];
                return function (data, search) {
                    search = search || '';
                    if (api.method === undefined || api.method == 'get') {
                        api.method = 'get';
                        data = {params: data};
                    }
                    return $http[api.method](api.api + search, data);
                };
            }

        }])
        //.filter('constantFilter', ['unkown', function (unkown) {
        //    return function (origin, constantName) {
        //        var $injector = angular.injector();
        //        debugger
        //        console.log($injector.has(constantName));
        //        //return origin !== undefined
        //        //    ? ($injector.get(constantName) || {})[origin]
        //        //    : unkown;
        //    }
        //}])
        .filter('picTypeFilter', ['picType', 'unkown', function (picType, unkown) {
            return function (origin) {
                return origin !== undefined ? picType[origin] : unkown;
            }
        }])
        .filter('isAbleFilter', ['isAble', 'unkown', function (isAble, unkown) {
            return function (origin) {
                return origin !== undefined ? isAble[origin] : unkown;
            }
        }])
        .controller('pictureManagerCtl', [
            '$rootScope',
            '$scope',
            '$timeout',
            '$document',
            'service',
            'pageIndex',
            'pageSize',
            'picType',
            'isAble',
            function ($rootScope, $scope, $timeout, $document, service, pageIndex, pageSize, picType, isAble) {

                $scope.editTemplate = require('../dialog/edit.html');

                $scope.Page = {
                    query: {
                        keyword: ''
                    },
                    pictures: [],
                    pagination: {
                        params: {
                            page: pageIndex,
                            per_page: pageSize
                        },
                        total: 0,
                        change: function (pageIndex, pageSize) {
                            var thiz = $scope.Page;
                            thiz.pagination.params.page = pageIndex;
                            thiz.pagination.params.per_page = pageSize;
                            thiz.list();
                        }
                    },
                    impl: {
                        filterSearchResult: function (res) {
                            var thiz = $scope.Page;
                            thiz.setItems(res.data.data);
                            thiz.pagination.total = res.data.total;
                        }
                    },
                    getItems: function () {
                        return this.pictures;
                    },
                    setItems: function (items) {
                        this.pictures = items;
                        return this.getItems();
                    },
                    list: function (pageIndex) {
                        var thiz = this;
                        service.list(thiz.getQuery(pageIndex))
                            .then(function (res) {
                                thiz.impl.filterSearchResult(res);
                            })
                    },
                    getQuery: function (pageIndex) {
                        return angular.extend({}, this.query, this.pagination.params,
                            {page: pageIndex === undefined ? this.pagination.params.page : pageIndex});
                    },
                    toggleAble: function (data) {
                        var thiz = this;
                        service.enable(angular.extend({}, data, {is_able: +!+data.is_able}))
                            .then(function () {
                                thiz.list(thiz.getQuery.page - 1);
                                if (data.is_able == '1') {
                                    ui.showSucTip('已禁用')
                                } else {
                                    ui.showSucTip('已启用')
                                }
                            });
                    },
                    delete: function (data) {
                        var self = this;
                        service.delete(data)
                            .then(function (res) {
                                self.reset();
                                ui.showSucTip('删除成功')
                            });
                    },
                    reset: function () {
                        this.list(0);
                    },
                    init: function () {
                        this.reset();
                    }
                };

                $scope.editor = {
                    save: function ($data) {
                        service.save($data)
                            .then(function (res) {
                                $scope.Page.reset();
                                ui.showSucTip('新增图片成功');
                            });
                    },
                    boforeShow: function ($dialog, $dialogScope, pic) {

                        $dialogScope.picType = picType;
                        $dialogScope.isAble = _.reduceRight(isAble, function (ret, item) {
                            ret.push(item);
                            return ret;
                        }, []);

                        $dialogScope.data.type = 1;
                        $dialogScope.data.is_able = 1;

                        angular.extend($dialogScope.data, pic);

                        // 图片上传
                        $(document)
                            .ready(function () {
                                var $img = $('<img/>').attr({
                                    src: $dialogScope.data.picture,
                                    width: '210px',
                                    height: '140px'
                                });
                                var $container = $('#preview_container');
                                $container.css({
                                    'display': 'block'
                                }).html('');

                                if ($dialogScope.data.picture) {
                                    $img.appendTo($container);
                                    $('#image_load').css('display', 'none');
                                }
                            })
                            .off('click', '#image_load, .image-upload-container .controllbar .upload')
                            .on('click', '#image_load, .image-upload-container .controllbar .upload', function () {
                                $('[role=image-upload-file-input]').val('').trigger("click");
                            })
                            .off('change', '[role=image-upload-file-input]')
                            .on('change', '[role=image-upload-file-input]', function () {
                                var uploadForm = $('[role=image-upload-file-form]');
                                uploadForm.ajaxSubmit({
                                    url: '/api/index.php?r=cms/article/media-edit',
                                    dataType: "json",
                                    success: function (data, status) {
                                        if (data.result) {
                                            var $img = $('<img/>').attr({
                                                src: data.path,
                                                width: '210px',
                                                height: '140px'
                                            });
                                            var $container = $('#preview_container');
                                            $container.css({
                                                'display': 'block'
                                            }).html('');
                                            $img.appendTo($container);
                                            $('#image_load').css('display', 'none');
                                            $('#image_url').val(data.path);
                                            $dialogScope.data.picture = data.path;
                                            $dialogScope.$applyAsync();
                                        }
                                    }
                                })
                            })
                            .off('mouseover', '.image-upload-container')
                            .on('mouseover', '.image-upload-container', function (event) {
                                $('.image-upload-container .controllbar').show();
                            })
                            .off('mouseout', '.image-upload-container')
                            .on('mouseout', '.image-upload-container', function (event) {
                                $('.image-upload-container .controllbar').hide();
                            })
                            .off('click', '.image-upload-container .controllbar .cancel')
                            .on('click', '.image-upload-container .controllbar .cancel', function (event) {
                                var $container = $('#preview_container');
                                $container.css({
                                    'display': 'none'
                                }).html('');
                                $('#image_url').val('');
                                $dialogScope.data.picture = '';
                                $dialogScope.$applyAsync();
                                $('#image_load').css('display', 'block');
                            });
                    }
                };

                $scope.Page.init();

            }]);
});
